<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>博客编辑页</title>

    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/edit.css">
    <link rel="stylesheet" href="css/components.css">
    <link rel="stylesheet" href="blog-editormd/css/editormd.css" />

</head>

<body>
<div class="nav">
    <div class="logo-container">
        <div class="logo-icon">B</div>
        <span class="blog-title">我的博客系统</span>
    </div>
    <div class="space"></div>
    <a class="nav-span" href="blog_list.html">主页</a>
    <a class="nav-span" href="blog_edit.html">写博客</a>
    <a class="nav-span" href="#" onclick="logout()">注销</a>
</div>
<div class="content-edit fade-in-up">
    <div class="push">
        <input type="text" name="title" id="title" placeholder="请输入博客标题" maxlength="100">
        <div class="edit-actions">
            <button type="button" id="saveDraft" onclick="saveDraft()" class="draft-btn">💾 保存草稿</button>
            <button type="button" id="preview" onclick="togglePreview()" class="preview-btn">👁️ 预览</button>
            <button type="button" value="发布文章" id="submit" onclick="submitBlog()">🚀 发布文章</button>
        </div>
    </div>
    <div class="editor-toolbar">
        <div class="word-count">
            <span id="titleCount">0</span>/100 字 | 内容: <span id="contentCount">0</span> 字
        </div>
        <div class="last-saved">
            <span id="lastSaved"></span>
        </div>
    </div>
    <!-- markdown 插件 html代码 -->
    <div id="editor">
        <textarea style="display:none;" id="content" name="content">## 在这里写下你的博客内容...

欢迎使用 Markdown 编辑器！你可以：

### 使用标题
- **粗体文本**
- *斜体文本*
- `代码块`

### 插入链接
[点击这里](https://example.com)

### 插入图片
![图片描述](https://via.placeholder.com/400x200)

### 代码块
```javascript
console.log('Hello, World!');
```

开始你的创作吧！</textarea>
    </div>
</div>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    // jQuery 加载失败的备用方案
    if (typeof jQuery === 'undefined') {
        document.write('<script src="blog-editormd/lib/jquery.min.js"><\/script>');
    }
</script>
<script src="blog-editormd/editormd.min.js"></script>
<script src="js/common.js"></script>
<script type="text/javascript">
    let editor; // 全局编辑器实例
    let isPreviewMode = false;
    let autoSaveTimer;
    
    // 页面初始化
    $(document).ready(function() {
        // 检查登录状态
        const userId = localStorage.getItem("loginUserId");
        const token = localStorage.getItem("userToken");
        
        if (!userId || !token) {
            showMessage('请先登录', 'warning');
            setTimeout(() => {
                location.href = 'blog_login.html';
            }, 1500);
            return;
        }
        
        // 初始化编辑器
        initEditor();
        
        // 聚焦到标题输入框
        $('#title').focus();
        
        // 加载草稿
        loadDraft();
        
        // 设置自动保存
        setupAutoSave();
        
        // 设置字数统计
        setupWordCount();
    });
    
    function initEditor() {
        try {
            editor = editormd("editor", {
                width: "100%",
                height: "calc(100vh - 250px)",
                path: "blog-editormd/lib/",
                syncScrolling: "single",
                placeholder: "在这里写下你的博客内容...",
                saveHTMLToTextarea: true,
                searchReplace: true,
                htmlDecode: "style,script,iframe|on*",
                emoji: true,
                taskList: true,
                tex: true,
                flowChart: true,
                sequenceDiagram: true,
                toolbar: true,
                lineNumbers: false,
                autoFocus: false,
                onchange: function() {
                    updateWordCount();
                }
            });
        } catch (error) {
            console.error('编辑器初始化失败:', error);
            showMessage('编辑器加载失败，请刷新页面重试', 'error');
        }
    }
    
    // 字数统计
    function setupWordCount() {
        $('#title').on('input', function() {
            const titleLength = $(this).val().length;
            $('#titleCount').text(titleLength);
            if (titleLength > 80) {
                $('#titleCount').css('color', '#f44336');
            } else {
                $('#titleCount').css('color', '#666');
            }
        });
    }
    
    function updateWordCount() {
        if (editor) {
            const content = editor.getMarkdown();
            const wordCount = content.replace(/\s/g, '').length;
            $('#contentCount').text(wordCount);
        }
    }
    
    // 自动保存功能
    function setupAutoSave() {
        $('#title').on('input', function() {
            clearTimeout(autoSaveTimer);
            autoSaveTimer = setTimeout(saveDraft, 3000);
        });
    }
    
    // 保存草稿
    function saveDraft() {
        const title = $('#title').val().trim();
        const content = editor ? editor.getMarkdown() : $('#content').val();
        
        if (!title && !content) return;
        
        const draft = {
            title: title,
            content: content,
            savedAt: new Date().toLocaleString()
        };
        
        localStorage.setItem('blogDraft', JSON.stringify(draft));
        $('#lastSaved').text('最后保存: ' + draft.savedAt);
        showMessage('草稿已保存', 'success', 1000);
    }
    
    // 加载草稿
    function loadDraft() {
        const draftData = localStorage.getItem('blogDraft');
        if (draftData) {
            try {
                const draft = JSON.parse(draftData);
                $('#title').val(draft.title || '');
                if (draft.savedAt) {
                    $('#lastSaved').text('最后保存: ' + draft.savedAt);
                }
                
                // 等待编辑器初始化完成后设置内容
                setTimeout(() => {
                    if (editor && draft.content) {
                        editor.setMarkdown(draft.content);
                    }
                }, 1000);
                
                if (draft.title || draft.content) {
                    showMessage('已加载上次的草稿', 'info', 2000);
                }
            } catch (error) {
                console.error('加载草稿失败:', error);
            }
        }
    }
    
    // 预览模式切换
    function togglePreview() {
        if (editor) {
            if (isPreviewMode) {
                editor.watch();
                $('#preview').text('👁️ 预览');
                isPreviewMode = false;
            } else {
                editor.unwatch();
                $('#preview').text('✏️ 编辑');
                isPreviewMode = true;
            }
        }
    }

    function submitBlog() {
        // 获取表单数据
        const title = $("#title").val().trim();
        const content = editor ? editor.getMarkdown() : $("#content").val();
        const userId = localStorage.getItem("loginUserId");
        
        // 前端验证
        if (!title) {
            showMessage('请输入博客标题', 'warning');
            $('#title').focus();
            return;
        }
        
        if (title.length > 100) {
            showMessage('标题长度不能超过100个字符', 'warning');
            $('#title').focus();
            return;
        }
        
        if (!content || content.trim() === '' || content.includes('在这里写下你的博客内容')) {
            showMessage('请输入博客内容', 'warning');
            return;
        }
        
        if (content.length > 50000) {
            showMessage('博客内容过长，请缩短内容', 'warning');
            return;
        }
        
        if (!userId) {
            showMessage('未找到用户信息，请重新登录', 'error');
            setTimeout(() => {
                location.href = 'blog_login.html';
            }, 1500);
            return;
        }
        
        // 显示加载状态
        showLoading("#submit", "发布中...");
        
        $.ajax({
            type: "post",
            url: "/blog/addBlog",
            contentType: "application/json",
            data: JSON.stringify({
                userId: userId,
                title: title,
                content: content
            }),
            success: function(result) {
                hideLoading("#submit");
                
                if (result && result.code && result.code.toString() === "SUCCESS" && result.data === true) {
                    // 清除草稿
                    localStorage.removeItem('blogDraft');
                    showMessage('博客发布成功！正在跳转...', 'success');
                    setTimeout(() => {
                        location.href = "blog_list.html";
                    }, 1000);
                } else {
                    showMessage(result.errMsg || '博客发布失败，请重试', 'error');
                }
            },
            error: function(xhr, status, error) {
                hideLoading("#submit");
                handleAjaxError(xhr, '博客发布失败，请重试');
            }
        });
    }
    
    // 键盘快捷键
    $(document).keydown(function(e) {
        // Ctrl+S 保存草稿
        if (e.ctrlKey && e.keyCode === 83) {
            e.preventDefault();
            saveDraft();
            return false;
        }
        
        // Ctrl+Enter 发布
        if (e.ctrlKey && e.keyCode === 13) {
            e.preventDefault();
            submitBlog();
            return false;
        }
        
        // Ctrl+P 预览
        if (e.ctrlKey && e.keyCode === 80) {
            e.preventDefault();
            togglePreview();
            return false;
        }
    });
    
    // 页面关闭前保存草稿
    window.addEventListener('beforeunload', function(e) {
        saveDraft();
    });
</script>
</body>

</html>